package com.rt.tmpt.security;

import com.rt.tmpt.dto.A2UserDto;
import com.rt.tmpt.service.IMenuService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Service(value = "myUserDetailService")
@Transactional
public class MyUserDetailServiceImpl implements UserDetailsService{

	@Resource private IMenuService menuService;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		Set<GrantedAuthority> authSet = new HashSet<>();

		A2UserDto userDto = menuService.getUserByLoginname(username);
		if(userDto == null){
			throw new UsernameNotFoundException("用户不存在！");
		}


		Set<String> authNameSet = userDto.getMenu2AuthList();
		for(String authName: authNameSet){
			SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authName);
			authSet.add(grantedAuthority);
		}

		Collection<GrantedAuthority> grantedAuths = authSet;

		String password = userDto.getPasswordBcrypt();
		boolean enabled = userDto.getDeleteFlag()==0? true: false;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		User userDetails = new User(username, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked,grantedAuths);


		return userDetails;
	}

}
